// Helper.js
// ====================

var fs = require('fs');
var config = require('./configController');

module.exports = {
	
	debug: function(text) {
		
		this.log(1,text);

	},
	
	info: function(text) {
	
		this.log(5,text);
		
	},

	error: function(text) {
	
		this.log(10,text);
		
	},
	
	/* spread the message to all loggers */
	log: function(level, text) {
		this.log2console(level, text);
		this.log2file(level, text);
	},
	
	/* log the message to the console */
	log2console: function(level, text) {
		
		var loglevel = config.read('log2ConsoleLevel');
		
		if (level<loglevel) {
			return;
		}
		
		console.log(text);
		
	},
	
	/* add date to logfile */
	log2FileAddDate: function() {
	
		var perDayLogging = config.read('log2FilePerDay');
		
		if (!perDayLogging) {
			return;
		}
	
		var logFile = config.read('log2FileFile');
		var d = new Date();

		logFile=logFile.replace('.log','_'+(d.getYear()-100)+'-'+(d.getMonth()+1)+'-'+d.getDate()+'.log');
		config.write('log2FileFile',logFile);

	},
	
	/* log the message to the logfile */
	log2file: function(level, text) {
	
		var loglevel = config.read('log2FileLevel');
		
		if (level<loglevel) {
			return;
		}
	
		var d = new Date();
		
		var msg = (d.getYear()-100)+'-'+(d.getMonth()+1)+'-'+d.getDate()+' ';
		msg += d.getHours()+':'+d.getMinutes()+':'+d.getSeconds();
		msg += ': '+text;
		
		try {
			var fd = fs.openSync(config.read('log2FileFile'), 'a+', '0666');
		  	fs.writeSync(fd, msg + '\n');
  			fs.closeSync(fd);
	  		fs.chmodSync(config.read('log2FileFile'),'0666');
  		}
  		catch (err) {
  			/* ignore */		
  		}
	},
};
